/* $Revision: $ $Date: $
 * 
 * Copyright (C) 2009 Robert Stephan
 * 
 * This file is part of *** CaCaO - Card Catalogs Online ***
 *
 * CaCaO is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CaCao is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cacao.client.data;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;


public class CaCaOHelper {
	/**
	 * creates the subpath to the given image file based on its name
	 * partitioned to use  max 10.000 files per folder
	 * 
	 * e.g. aki_00023456.jpg is stored as
	 * aki/0/0/0/2/aki_00023456.jpg
	 * @param filename
	 * @return the path
	 */
	
	public static String generatePath(String filename, int lastChunkLength, String extension, boolean debug){
		String catalog = filename.substring(0,filename.indexOf("_"));
		String count = filename.substring(filename.indexOf("_")+1);
		if(debug){
			lastChunkLength=3;
			filename = generateImageID("ALL", Integer.parseInt(count) % 100, 4);
			count = filename.substring(filename.indexOf("_")+1);
			catalog = filename.substring(0,filename.indexOf("_"));
		}
		StringBuffer path = new StringBuffer(catalog);
		for(int i=0;i<count.length()-lastChunkLength;i++){
			path.append("/").append(count.substring(i,i+1));
		}
		path.append("/").append(filename).append(".").append(extension);
		return path.toString();
	}
	
	public static String generateImageID(String prefix, int nr, int length){
		String count = Integer.toString(nr);
		while(count.length() < length) {
		 count = "0" + count;
		}
		return prefix+"_"+count;
	}
	
	public static String getCatalogSpecificString(String message, String catalogCode){
    	JSONValue jsonObjectValue = JSONParser.parseStrict(message);
		JSONObject jsonObject = jsonObjectValue.isObject();
		JSONValue jsonValue = jsonObject.get(catalogCode);
		if(jsonValue!=null){
			return jsonValue.isString().stringValue();
		}
		else{
			return "";
		}
	}

	public static void main(String[] args){
		System.out.println("aki_0123456.png : "+generatePath("aki_0123456", 3, "png", true));
		System.out.println("aki_12345.png : "+generatePath("aki_12345", 4, "png", true));
		System.out.println("mk_12.jepg : "+generatePath("mk_12", 5, "jepg", true));
	}
}
